/**
 * @desc 记账本
 * @param {Number} money 金额
 * @param {Number} type 0=收入; 1=支出
 * @param {Number} way 收支方式的代码
 * @param {Number} date 日期
 * @param {String} remark 备注
 */

// create table
const d = new Date().getTime()
const t = []
for (let i = 0; i < 200; i++) {
  t.push({
    money: Math.floor(Math.random() * 500 + 2),
    type: 0.5 - Math.random() > 0 ? 0 : 1,
    way: Math.floor(Math.random() * 6),
    date:
      d -
      i * (1000 * 60 * 60 * 6) -
      Math.floor(Math.random() * 12) * (1000 * 60 * 60) -
      Math.floor(Math.random() * 60) * (1000 * 60),
    remark: ''
  })
}

const state = {
  table: t.reverse()
}

const getters = {
  monthStatistics(state) {
    const income = Array(12)
      .fill(null)
      .map((v, i) => {
        return state.table
          .filter(item => {
            return new Date(item.date).getMonth() === i && !item.type
          })
          .reduce((pre, curr) => pre + curr.money, 0)
      })
    const expenditure = Array(12)
      .fill(null)
      .map((v, i) => {
        return state.table
          .filter(item => {
            return new Date(item.date).getMonth() === i && item.type
          })
          .reduce((pre, curr) => pre + curr.money, 0)
      })
    return { income, expenditure }
  },

  yearStatistics(state) {
    const currYear = new Date().getFullYear()
    const income = Array(3)
      .fill(null)
      .map((v, i) => {
        return state.table
          .filter(item => {
            return new Date(item.date).getFullYear() === currYear - i && !item.type
          })
          .reduce((pre, curr) => pre + curr.money, 0)
      })
      .reverse()
    const expenditure = Array(3)
      .fill(null)
      .map((v, i) => {
        return state.table
          .filter(item => {
            return new Date(item.date).getFullYear() === currYear - i && item.type
          })
          .reduce((pre, curr) => pre + curr.money, 0)
      })
      .reverse()
    return { income, expenditure }
  }
}

const mutations = {}

export default {
  namespaced: true,
  state,
  getters,
  mutations
}
